package com.it.sun.easychat.framework.security.filter;

import com.alibaba.fastjson.JSON;
import com.it.sun.easychat.model.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author sunmannian
 * @ClassName com.it.sun.easychat.framework.security.filter.UsernamePasswordAuthenticationFilter
 * @Date 2020/5/24 19:51
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/24
 */
@Slf4j
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public UsernamePasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login*", HttpMethod.POST.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws
            AuthenticationException, IOException {
        LoginVO loginVO = JSON.parseObject(request.getInputStream(),
                StandardCharsets.UTF_8,
                LoginVO.class);
        Assert.notNull(loginVO, "用户信息不能为空");
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginVO.getUsername(),
                loginVO.getPassword());
        return this.getAuthenticationManager().authenticate(authentication);
    }
}
